/*
 * tqxs.js
 * 天气形势
 */
;
(function (call) {
    var main = {
        baseUrl: CafeJS.CXT,
        mapId: "tjMap",
        playList: null,
        datepicker: null,
        legendpicker: null,
        currentStationId: '',
        isFirstGetRadarPubLatestTime: true,
        isFirstGetSingleRadarLatestTime: true,
        router: {
            getRadarData: 'zhfx/rader/queryOneStationRadaData', //单个雷达
            getCappiData: 'zhfx/rader/queryRadaDataByTimeList', //雷达组网
            getRadarPubLatestTime: 'zhfx/rader/queryGroupNetLatestTime', //雷达组网
			getRadarRaw:'/weatherelecheck/queryRadarRawController/getRadarRaw',//swan3.0
            queryModelGridDataByCam:'sjyb/queryModelGridDataByCam',//双偏振雷达
            getSingleRadarLatestTime: 'zhfx/rader/queryOneStationRadaDataLatestTime', //单个雷达
            productcfg: "/business/common/json/product.json",
            queryRoseRadarNewTime:'zhfx/rader/queryRoseRadarNewTime',//获取宝坻最新时间
            queryRoseRadarData:'zhfx/rader/queryRoseRadarData',//获取宝坻数据
        },
        init: function () {
            this.initView();
            this.bindEvt();
        },
        initView: function () {
            var that = this;
            that.initDatePicker();
            $.getJSON(that.router.productcfg, function (cfg) {
                that.initProductList(cfg);
            })
        },
        // 初始化图例
        initLegentpicker: function (ele, appendTo) {
            var that = this;
            var layers = that.getModels(ele);
            var layerIds = [];
            $.each(layers, function (i, m) {
                layerIds.push(m.id);
            });

            CafeJS.legentPicker = CafeJS.Legentpicker({
                appendTo: appendTo,
                gisId: that.mapId,
                layerId: layerIds,
                totalWidth: 400,
                h_legend: 15,
                type: ele.category == 'single-radar' ? 'index' : 'value',
                seq: 'decrease',
                productId: ele.color_id,
                isShowSlider: true
            });
        },
        // 初始化产品列表
        initProductList: function (cfg) {
            var that = this
            var params = {
                container: '.product-content.dlcp',
                data: cfg.radar,
                eleClick: function (ele, oldEle, selected) {
                    var name = ele.ele_name;
                    var eleid = ele.ele_id; //当前要素id
                    var oldId = oldEle.ele_id; // 上一个选中要素
                    var category = ele.category; //当前要素的类型
                    var isSK = ele.isSK;

                    that.clearGridLayer(oldId);

                    var startTime = that.datepicker.getVal();
                    var pro = {
                        name: name,
                        time: startTime,
                        bussitype: 'dlcp',
                        ele: ele,
                        isGrid: true,
                        isSK: isSK
                    }
                    var call = function (newTime) {
                        if (newTime)
                            pro.time = newTime;
                        that.clearGridLayer(oldEle.ele_id);
                        CafeJS.layerManage.removeLayer({
                            name: oldEle.ele_name
                        }); // 删除上一个选中要素的图层
                        // 增加产品图层
                        that.addLayerManage(pro);
                        that.queryEleData(ele, pro.time);
                    }
                    if (selected) { // 获取最新时间
                        if (category == 'single-radar') {
                            if (that.currentStationId == '' && that.isFirstGetSingleRadarLatestTime) {
                                that.getSingleRadarLatestTime(startTime, eleid, call);
                                that.currentStationId = $('.radar-station-tab dt.active').data('statcd');
                                that.isFirstGetSingleRadarLatestTime = false;
                            } else {
                                call();
                            }
                        } else {
                            if (that.isFirstGetRadarPubLatestTime) {
                                that.getRadarPubLatestTime(startTime, eleid, call);
                                that.isFirstGetRadarPubLatestTime = false;
                            } else {
                                call();
                            }
                        }
                    } else {
                        that.clearGridLayer(eleid);
                        CafeJS.layerManage.removeLayer(pro); // 删除当前要素的图层
                        if (category == 'single-radar') {
                            that.currentStationId = '';
                        }
                    }
                }
            };
            CafeJS.analysis(params);
        },
        // 获取单站雷达最新时间
        getSingleRadarLatestTime: function (time, elementId, call) {
            var statcd = $('.radar-station-tab dt.active').data('statcd');
            var angle = $('.radar-angle-tab dt.active').first().data('angle');
            var param = {
                stationId: statcd,
                productId: elementId,
                proSeq: angle
            }
           
            var latestTime = time;
            if (!loading.isExist())
                loading.add();
            $.ajax({
                url: this.router.getSingleRadarLatestTime,
                type: 'get',
                data: param,
                dataType: 'json'
            }).done(function (res) {
                if (res.isSuccess && res.data)
                    latestTime = dateUtil.convertStringToDate7(res.data, 'yyyy-MM-dd hh:mm');
            }).always(function () {
                loading.remove();
                if (call) call(latestTime);
            })
        },
        // 获取雷达组网最新起报时间
        getRadarPubLatestTime: function (time, elementId, call) {
            var qbTime = time;
            var _this = this;
            var param = {
                element: elementId,
                queryTime:new Date(qbTime).format('yyyyMMddhhmm00'),
                backMinutes:"120"
            }
            if (!loading.isExist())
                loading.add();
            $.ajax({
                url: this.router.getRadarPubLatestTime,
                type: 'get',
                data: param,
                dataType: 'json'
            }).done(function (res) {
                debugger
                if (res.isSuccess && res.data){
                    qbTime = dateUtil.convertStringToDate7(res.data, 'yyyy-MM-dd hh:mm');
                }else{
                    qbTime =  new Date(new Date(new Date().setMinutes(Math.floor(new Date().getMinutes()/6)*6)).getTime() - 1000*60*36).format("yyyy-MM-dd hh:mm");
                }
            }).always(function () {
                loading.remove();

                if (call) call(qbTime);
            })
        },
        // 初始化时间控件
        initDatePicker: function () {
            var _this = this;
            debugger
			let date = new Date(new Date(new Date().setMinutes(Math.floor(new Date().getMinutes()/6)*6)).getTime() - 12*60*1000);
            this.datepicker = CafeJS.Datepicker({
                appendTo: "#datepicker-dlcp",
                type: 3,
                curDate:$("#userInfo").data("isMatchuser")?"2022-07-26 10:00":date,
                timeInterval: 6,
                call: function (val) {
                    _this.queryMultiEleData();
                }
            });
            $("#datepicker-dlcp").show();
        },
        // 初始化播放列表
        initPlayList: function (pro) {
            var that = this;
            var startTime = pro.time;

            var layers = this.getModels(pro.ele);
            var interval = pro.ele.interval || 6;
			
			this.playList = CafeJS.Timeline3({
				appendTo: "#a-m-timeline",
				curDate: startTime,
				type: 1,
				pro: pro,
				dateOpt: {
					dateFmt: 'yyyy-MM-dd hh:mm',
					timeInterval: interval,
					customHm: []
				},
				timeInterval: interval,
				layers: layers,
				gisId: that.mapId,
				call: function (pro) {
					CafeJS.layerManage.updateLayer(pro);
					that.queryEleData(pro.ele, pro.time);
				},
				getPlayData: function (pro, timeArr) {
					that.queryEleData(pro.ele, timeArr);
				}
			});
        },
        // 查询已选择要素
        queryMultiEleData: function () {
            var that = this;
            var pro, time;
            $(".dlcp .product-list li.active").each(function (i, ele) {
                pro = $(ele).data('pro');
                time = that.calcStartTime(pro);
                CafeJS.layerManage.updateLayerTime(time, 'dlcp', null, pro.ele_id);
                that.queryEleData(pro, time);
            });
        },
        // 查询要素数据
        queryEleData: function (ele, time) {
            var that = this;
            var type = ele.type;
            if (type == 'CAPPI') {
                that.queryCappiData(ele, time);
            } else if ("swan" == type){
				that.getRadarRaw(ele, time);
			} else if ("doublepz" == type){
                that.getRadardoublepzRaw(ele, time);
            }else {
                if($('.radar-station-tab dt.active').data('statcd') == "Z9025"){
                     that.queryRoseRadarNewTime(ele, time);
                }else{
                     that.queryRadarData(ele, time);
                }
               
            }
        },
        queryRoseRadarNewTime(pro, time){
            var that = this;
            var newTime = time;
            var element = pro.ele_id;
            var statcd = $('.radar-station-tab dt.active').data('statcd');
            var angle = $('.radar-angle-tab dt.active').first().data('angle');
            if (time.indexOf(',') == -1) {
                time = new Date(time).format('yyyyMMddhhmm');
            }
            var params = {
                queryTime: time,
                stationId: statcd,
                productId: element,
                proSeq: angle
            }
            $.ajax({
                url: this.router.queryRoseRadarNewTime,
                type: 'get',
                data: params,
                dataType: 'json'
            }).done(function (res) {
                if (res.isSuccess && res.data){
                    debugger
                    newTime = res.data.substr(0, 4)+"-"+res.data.substr(4, 2)+"-"+res.data.substr(6, 2)+" "+res.data.substr(8, 2)+":"+res.data.substr(10, 2)+":"+res.data.substr(12, 2)
                    CafeJS.layerManage.updateLayerTime(newTime, 'dlcp', null, pro.ele_id);
                }
                that.queryRadarData(pro, newTime);    
                
            }).always(function () {
               
            })
        },
        // 获取单站雷达数据
        queryRadarData: function (pro, time) {
            var that = this;
            var element = pro.ele_id;
            var statcd = $('.radar-station-tab dt.active').data('statcd');
            var angle = $('.radar-angle-tab dt.active').first().data('angle');
            if (time.indexOf(',') == -1) {
                time = new Date(time).format('yyyyMMddhhmmss');
            }
            var params = {
                queryTimes: time,
                stationId: statcd,
                productId: element,
                proSeq: angle
            }
            if (time.indexOf(',') > -1)
                loading.add();
            CafeJS.ajax({
                url: "Z9025"==statcd ? that.router.queryRoseRadarData:that.router.getRadarData,
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
        //获取双偏振雷达数据
        getRadardoublepzRaw: function (pro, time) {
            var that = this;
            if (time.indexOf(',') == -1) {
                time = new Date(time).format('yyyy-MM-dd hh:mm:ss');
            }
            var element = pro.ele_id;
            var params = {
                queryTime: time,
                modeType:"CAMS",
                element: element,
                height:"500",
                period:6,
                dataType:"nc",
                interval:3
            }
            if (time.indexOf(',') > -1)
                loading.add();
            CafeJS.ajax({
                url: that.router.queryModelGridDataByCam,
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    debugger
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
		//获取swan3.0数据
		getRadarRaw: function (pro, time) {
            var that = this;
            if (time.indexOf(',') == -1) {
                time = new Date(time).format('yyyyMMddhhmmss');
            }
            var element = pro.ele_id;
            var params = {
                skTime: time,
                element: element
            }
            if (time.indexOf(',') > -1)
                loading.add();
            CafeJS.ajax({
                url: that.router.getRadarRaw,
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
        // 获取雷达数据
        queryCappiData: function (pro, time) {
            var that = this;
            if (time.indexOf(',') == -1) {
                time = new Date(time).format('yyyyMMddhhmmss');
            }
            var element = pro.ele_id;
            var params = {
                queryTime: time,
                element: element
            }
            if (time.indexOf(',') > -1)
                loading.add();
            CafeJS.ajax({
                url: that.router.getCappiData,
                params: params,
                type: "GET",
                success: function (e) {
                    loading.remove();
                    var arrayBuffer = e.response;
                    if (arrayBuffer.byteLength === 0) {
                        alert("该时间点没有数据");
                        that.clearGridLayer(element);
                        return;
                    }
                    that.drawGridRawMap(arrayBuffer, pro);
                }
            })
        },
        // 绘制格点色斑图
        drawGridRawMap: function (data, ele) {
            var typeArr = this.getModels(ele);
            var colorObj = CafeJS.Legentconfig().cfg()[ele.color_id];
            // 显示色斑和数值
            GIS.GridShow.showByTypes_raw(this.mapId, typeArr, data, {}, colorObj);
            CafeJS.legentPicker.updateLegentRange(typeArr,this.mapId);
        },
        // 增加产品图层
        addLayerManage: function (pro) {
            var that = this;
            if (CafeJS.layerManage) {
                CafeJS.layerManage.addLayer(pro);
            } else {
                CafeJS.layerManage = CafeJS.LayerManage({
                    appendTo: "#c-b-layermanage",
                    mapId: that.mapId,
                    proInfo: pro,
                    call: function (pro) {
                        CafeJS[pro.bussitype].initPlayList(pro);
                    },
                    close: function (pro) {
                        CafeJS[pro.bussitype].delLayer(pro);
                    }
                })
            }
            that.initLegentpicker(pro.ele, '.cafe-layer-item.active');
        },
        // 根据时间间隔获取开始时间
        calcStartTime: function (ele) {
            var time = new Date(this.datepicker.getVal());
            switch (ele.interval) {
                case 60:
                    time.setMinutes(0);
                    break;
            }
            return time.format('yyyy-MM-dd hh:mm');
        },
        // 删除图层后取消要素选择
        delLayer: function (pro) {
            var eleid = pro.ele.ele_id;
            $(".dlcp .product-list li.active").each(function () {
                if ($(this).data('pro').ele_id == eleid) {
                    $(this).click();
                    return false;
                }
            })
        },
        // 清除格点GIS图层
        clearGridLayer: function (eleid) {
            var layerIds = [];
            GLMap.layerIds.forEach(function (layerId) {
                if (layerId.indexOf('dlcp-layer') != -1 && layerId.lastIndexOf(eleid) != -1) {
                    layerIds.push(layerId);
                }
            })
            GIS.LayerControll.deleteLayer(this.mapId, layerIds);
        },
        // 获取要素样式
        getModels: function (ele) {
            if (!ele.models) return;
            var models = [];
            $.each(ele.models.split(","), function (i, m) {
                var layerId = "dlcp-layer-" + m + "-" + ele.ele_id;
                models.push({
                    type: m,
                    visible: true,
                    uv: false,
                    wd: true,
                    id: layerId
                });
            });
            return models;
        },
        bindEvt: function () {}
    };
    if (typeof call === 'function') {
        CafeJS.dlcp = main;
        call(main);
    }

})(function (main) {
    CafeJS.models(['datepicker', 'legentpicker', 'legentconfig', 'squarelegend', 'ajax', 'timeLine2', 'timeLine3'], function () {
        main.init();
    });
});